package com.yunmai.web.services.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.talanlabs.avatargenerator.Avatar;
import com.talanlabs.avatargenerator.IdenticonAvatar;
import com.yunmai.web.domain.AccountDetailEntity;
import com.yunmai.web.exception.BusinessResponseException;
import com.yunmai.web.exception.error.ErrorMessageResponse;
import com.yunmai.web.repositories.IAccountDetailMapper;
import com.yunmai.web.services.IAccountDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WangChen
 * @since 2021-03-12
 */
@Service
public class AccountDetailServiceImpl extends ServiceImpl<IAccountDetailMapper, AccountDetailEntity> implements IAccountDetailService {

    private static final Logger logger = LoggerFactory.getLogger(AccountDetailServiceImpl.class);

    @Autowired
    private IAccountDetailService accountDetailService;

    @Override
    public AccountDetailEntity create(String authId, String accountId) {

        Avatar avatar = IdenticonAvatar.newAvatarBuilder().build();
        String base64DataUri = ImgUtil.toBase64DataUri(avatar.create(Long.parseLong(accountId)), ImgUtil.IMAGE_TYPE_JPG);

        AccountDetailEntity accountDetailEntity = new AccountDetailEntity();

        accountDetailEntity.setAccountId(accountId);
        accountDetailEntity.setAvatar(base64DataUri);
        accountDetailEntity.setName(authId);

        accountDetailService.save(accountDetailEntity);

        return accountDetailEntity;
    }

    @Cacheable(cacheNames = "cache_account_detail", key = "#accountId")
    @Override
    public AccountDetailEntity find(String accountId) {

        LambdaQueryWrapper<AccountDetailEntity> wrapper = Wrappers.lambdaQuery(AccountDetailEntity.class)
                .eq(AccountDetailEntity::getAccountId, accountId);

        AccountDetailEntity accountDetailEntity = accountDetailService.getOne(wrapper);

        if (ObjectUtil.isEmpty(accountDetailEntity)){
            logger.info("[AccountDetailServiceImpl] find is null!");
            throw new BusinessResponseException(ErrorMessageResponse.ACCOUNT_NOT_EXIST.convert());
        }

        return accountDetailEntity;
    }
}
